package com.zhx.rmq.provider.controller;

import com.zhx.rmq.utils.HttpClientUtil;
import lombok.Value;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

@RestController
@Slf4j
public class TaskController {

    private static int corePoolSize = Runtime.getRuntime().availableProcessors();
    /**
     * 创建线程池  调整队列数 拒绝服务
     */
    private static ThreadPoolExecutor executor = new ThreadPoolExecutor(
            corePoolSize,
            corePoolSize + 1,
            10L,
            TimeUnit.SECONDS,
            new LinkedBlockingQueue<>(1000));

    @Autowired
    RabbitTemplate rabbitTemplate;  //使用RabbitTemplate,这提供了接收/发送等等方法

    @GetMapping("/sendDirectMessage")
    public String sendDirectMessage() {
        String messageId = String.valueOf(UUID.randomUUID());
        String messageData = "test message, hello!";
        String createTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        Map<String, Object> map = new HashMap<>();
        map.put("messageId", messageId);
        map.put("messageData", messageData);
        map.put("createTime", createTime);
        //将消息携带绑定键值：directRouting 发送到交换机TestDirectExchange
        rabbitTemplate.convertAndSend("directExchange", "directRouting", map);
        return "ok";
    }

    @GetMapping("/batch/sendMsg")
    public String startLock() {
        int skillNum = 2;
        final CountDownLatch latch = new CountDownLatch(skillNum);
        log.info("开始");
        for (int i = 0; i < skillNum; i++) {
            int finalI = i;
            Runnable task = () -> {
                //使用公平锁机制,等待时间长的优先获得时间片
                // TODO 业务：测试同时退款
                String messageId = String.valueOf(UUID.randomUUID());
                String createTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
                Map<String, Object> map = new HashMap<>();
                map.put("messageId", messageId);
//                map.put("order_no","AQAApkIKIb1-FTYJBnDxBOhoOdtf");
                map.put("order_no","test1");
                map.put("createTime", createTime);
                //将消息携带绑定键值：directRouting 发送到交换机TestDirectExchange
                rabbitTemplate.convertAndSend("directExchange", "directRouting", map);
                log.info("用户:[{}] 发起退款申请", finalI);
                latch.countDown();
            };
            executor.execute(task);
        }
        try {
            latch.await();// 等待所有人任务结束
            log.info("一共:[{}]个退款申请", skillNum);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "Result.ok()";
    }


    @GetMapping("/batch/sendMsg2")
    public String startLock2() {
        int skillNum = 2;
        final CountDownLatch latch = new CountDownLatch(skillNum);
        log.info("开始");
        for (int i = 0; i < skillNum; i++) {
            int finalI = i;
            Runnable task = () -> {
                //使用公平锁机制,等待时间长的优先获得时间片
                // TODO 业务：测试同时退款
                HashMap<String, String> map = new HashMap<>();
                map.put("order_no","AQAAvEDkHr1uhXBkBnDxBOhoOdtf");
                //订单退款
                String s = HttpClientUtil.doGet("http://localhost:6301/applebackstage/order/refund",map);
                log.info("用户:[{}]发起退款申请  处理结果: [{}]", finalI,s);
                latch.countDown();
            };
            executor.execute(task);
        }
        try {
            latch.await();// 等待所有人任务结束
            log.info("一共:[{}]个退款申请", skillNum);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "Result.ok()";
    }

    @GetMapping("/batch/sendMsg3")
    public String startLock3() {
        log.info("开始");
                // TODO 业务：测试同时退款
                HashMap<String, String> map = new HashMap<>();
                map.put("order_no","AQAApkIKIb1-FTYJBnDxBOhoOdtf");
                //订单退款
                String s = HttpClientUtil.doGet("http://localhost:6301/applebackstage/order/refund",map);
                log.info("用户:[]发起退款申请  处理结果: [{}]",s);
        return "Result.ok()";
    }

    @GetMapping("/sendTopicMessage1")
    public String sendTopicMessage1() {
        String messageId = String.valueOf(UUID.randomUUID());
        String messageData = "message: M A N ";
        String createTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        Map<String, Object> manMap = new HashMap<>();
        manMap.put("messageId", messageId);
        manMap.put("messageData", messageData);
        manMap.put("createTime", createTime);
        rabbitTemplate.convertAndSend("topicExchange", "topic.man", manMap);
        return "ok";
    }

    @GetMapping("/sendTopicMessage2")
    public String sendTopicMessage2() {
        String messageId = String.valueOf(UUID.randomUUID());
        String messageData = "message: woman is all ";
        String createTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        Map<String, Object> womanMap = new HashMap<>();
        womanMap.put("messageId", messageId);
        womanMap.put("messageData", messageData);
        womanMap.put("createTime", createTime);
        rabbitTemplate.convertAndSend("topicExchange", "topic.woman", womanMap);
        return "ok";
    }

    @GetMapping("/sendFanoutMessage")
    public String sendFanoutMessage() {
        String messageId = String.valueOf(UUID.randomUUID());
        String messageData = "message: testFanoutMessage ";
        String createTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        Map<String, Object> map = new HashMap<>();
        map.put("messageId", messageId);
        map.put("messageData", messageData);
        map.put("createTime", createTime);
        rabbitTemplate.convertAndSend("fanoutExchange", null, map);
        return "ok";
    }





}